<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class PhoneController extends Controller
{
	//显示
    public function getIndex(Request $request)
    {
        if($request['name']){
            //搜索分页
            $res = DB::table('person')
            ->join('phone','phone.PersonId','=','person.id')
            ->where('person.PersonName','like','%'.$request['name'].'%')
            ->paginate(4);
        }else{
            //所有分页

            $res = DB::table('person')
            ->join('phone','phone.PersonId','=','person.id') 
            ->orderBy('phone.id','asc')
            ->paginate(4);

        }
        // dd($info);
        $info = $request -> all();
        // dd($res);
        return view('phone.phone',['res'=>$res,'info'=>$info]);
    }


    //添加
    public function getAdd()
    {
        return view('/phone/add');
    }

    //执行添加
    public function postInsert(Request $request)
    {
        //表单验证
        $this->validate($request, [
        'PersonName' => 'required|exists:person,PersonName',
        'TelPhone' => 'required|unique:phone,TelPhone|numeric',
        'Remark' => 'required',
        ],[
        'PersonName.required'=>'联系人不能为空',
        'PersonName.exists'=>'联系人不存在',
        'TelPhone.required'=>'电话号码不能为空',
        'TelPhone.unique'=>'电话号码已存在',
        'TelPhone.numeric'=>'电话号码必须为数字',
        'Remark.required'=>'备注不能为空',
        ]);
        $res = $request->only('TelPhone','Remark');
        $id = $request->only('PersonName');
        $res['PersonId'] = DB::table('person')->where('PersonName',$id['PersonName'])->value('id');
        // dd($res);
        DB::table('phone')->insert($res);
        return redirect('/phone');
    }


    //编辑
    public function getEdit($id)
    {
        //查询
        $res = DB::table('phone')
        ->join('person','phone.PersonId','=','person.id')
        ->where('phone.id',$id)
        ->select('person.PersonName','phone.id','phone.TelPhone','phone.Remark')
        ->get();
        // dd($res);
        return view('/phone/edit',['res'=>$res]);
    }

    //修改
    public function postUpdate(Request $request)
    {
        //表单验证
        $this->validate($request, [
        'TelPhone' => 'required',
        'Remark' => 'required',
        ],[
        'TelPhone.required'=>'电话号码不能为空',
        'Remark.required'=>'备注不能为空',
        ]);
        $res = $request->only('id','TelPhone','Remark');
        // dd($res);
        //执行修改
        DB::table('phone')->where('id',$res['id'])->update($res);
        return redirect('/phone');

    }

    //删除
    public function getDel($id)
    {
        //执行删除
        DB::table('phone')->where('id',$id)->delete();
        return redirect('/phone');
        
    }

}
